<script setup>
import topNav from "../../components/topNav.vue";
import { onMounted, reactive, ref, getCurrentInstance, computed } from "vue";
import { onLoad, onReachBottom, onShow } from "@dcloudio/uni-app";
import { useCodeStore } from "@/stores/code.js";
import picView from "../../components/pic/index.vue";
import { operation } from "@/utils/num.js";
import { appCodeByDetail, orderVerify } from "@/services/cancellation.js";

// @param op { string } 运算类型，有加减乘除（add / subtract / multiply / divide）

import {
  appCategory,
  supplierSelector,
  productCreate,
  appProductDetail,
  appProductDisable,
  appProductEnable,
  productUpdate,
  appProductCode,
  appUnit,
} from "@/services/goods";

import { base_URL } from "@/utils/http";
const selectGoods = ref({});
const sourceNum = ref(1);
const targetNum = ref(1);
const verifyCode = ref("");
const order_id = ref("");
onLoad((option) => {
  console.log(option.code);

  if (option.code) {
    let OBJ = getCodeUrl(option.code);
    console.log(OBJ);
    verifyCode.value = OBJ.cal_code;
    if (verifyCode.value) {
      getCodeByDetail();
    }
  }
});
onShow(() => {
  isTK.value = false;
});

const isCB = ref(false);
const goodsList = ref([]);
const getCodeUrl = (str) => {
  let code = decodeURIComponent(str).split("?")[1];

  let arr = code.split("&");
  let retArr = {};
  arr.forEach((item) => {
    let [key, value] = item.split("=");
    retArr[key] = value;
  });
  console.log(code, arr, retArr);
  return retArr;
};
const showP = ref(false);
const getCodeByDetail = async () => {
  if (!verifyCode.value) {
    uni.showToast({
      title: "请输入/扫描核销码",
      icon: "none",
    });
    return;
  }
  try {
    let res = await appCodeByDetail({ verifyCode: verifyCode.value });
    console.log(res);
    res.data.orderProduct.forEach((item) => {
      item.total_num = item.product_num;
      // item.num = item.product_num;
      if (item.is_refund >= 1) {
        if (item.refund_num <= 0) {
          item.product_num = 0;
          item.num = 0;
        } else {
          item.num = item.refund_num;
          item.product_num = item.refund_num;
        }
      } else {
        item.num = item.product_num;
      }
    });

    goodsList.value = res.data.orderProduct;
    order_id.value = res.data.order_id;
    showP.value = true;
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
  }
};

const goadd = async () => {
  if (isCB.value) {
    return;
  }
  isCB.value = true;
  try {
    const res = await UnpackCreate({
      sourceProductId: selectGoods.value.sourceProductId,
      sourceNum: sourceNum.value,
      targetNum: targetNum.value,
      targetProductId: selectGoods.value.id,
    });

    if (res.code == 200) {
      uni.showToast({
        title: "拆包成功",
        icon: "success",
      });
      setTimeout(() => {
        uni.navigateBack();
        isCB.value = false;
      }, 1000);
    } else {
      isCB.value = false;
    }
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
    isCB.value = false;
  }
};

const goList = () => {
  uni.navigateTo({
    url: "/pages/cancellation/list/index",
  });
};

const scanFun = () => {
  // #ifdef H5
  uni.navigateTo({ url: "/pages/code_sand/index?type=cancellation" });
  // #endif
  // #ifdef APP-PLUS
  // 允许从相机和相册扫码
  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                // autoZoom: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);

                  let OBJ = getCodeUrl(res.result);

                  verifyCode.value = OBJ.cal_code;
                  if (verifyCode.value) {
                    getCodeByDetail();
                  }
                },
              });
            }
          }
        );
      }
    });
    return;
  }
  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    // autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      let OBJ = getCodeUrl(res.result);

      verifyCode.value = OBJ.cal_code;
      if (verifyCode.value) {
        getCodeByDetail();
      }
    },
  });
  // #endif
};

const isTK = ref(false);
const goRecord = async () => {
  if (isTK.value) {
    return;
  }
  isTK.value = true;

  let datas = [],
    isU = false;
  goodsList.value.forEach((item) => {
    if (item.num > 0) {
      datas.push({
        id: item.order_product_id,
        num: item.num,
      });
      isU = true;
    }
  });
  if (!isU) {
    uni.showToast({
      title: "请选择核銷商品",
      icon: "none",
    });
    return;
  }
  console.log("datas", datas);

  try {
    let res = await orderVerify({
      id: order_id.value,
      data: datas,
      verifyCode: verifyCode.value,
    });
    console.log("核销结果", res);

    if (res.code == 200) {
      uni.showToast({
        title: "核销成功",
        icon: "success",
      });
      isTK.value = false;
      showP.value = false;
      // setTimeout(() => {
      //   uni.navigateTo({
      //     url: "/pages/cancellation/list/index",
      //   });
      //      isTK.value = false;
      // }, 1500);
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
      });
      isTK.value = false;
    }
  } catch (e) {
    isTK.value = false;
    uni.showToast({
      title: e.msg,
      icon: "none",
    });
  }
};
</script>

<template>
  <topNav
    :title="type == 'add' ? '订单核销' : '订单核销'"
    @save="saveFun"
    rType="save"
  ></topNav>

  <view class="content">
    <view class="top">
      <image src="@/static/cancellation/newca.png" mode="widthFix" />
    </view>

    <view class="scan">
      <view class="scan-k" @click="scanFun">
        <image src="@/static/index/scan.png" mode="scaleToFill" />
        <view> 扫码核销 </view>
      </view>
      <view class="scan-to"> 点击扫描二维码 </view>
    </view>

    <view class="search">
      <view class="search-k">
        <image src="@/static/index/eidt.png" mode="scaleToFill" />
        <input type="text" v-model="verifyCode" placeholder="请输入核销码" />
        <!-- <text class="search-to" @click="getCodeByDetail">搜索</text> -->
      </view>

      <button class="bt" @click="getCodeByDetail">确认</button>
    </view>

    <view class="list-to" v-permission="['shop:mulin:order:list']">
      <text @click="goList">核销订单列表</text>
      <up-icon
        @click="goList"
        name="arrow-right"
        color="#86909c"
        size="40rpx"
      ></up-icon>
    </view>
  </view>

  <up-popup
    :show="showP"
    :closeOnClickOverlay="true"
    mode="bottom"
    @close="showP = false"
    round="15rpx"
    :closeable="true"
  >
    <view class="sel_p">
      <view class="sel_p-title">订单核销</view>

      <view>
        <scroll-view scroll-y="true" class="scroll-Y">
          <view
            class="scroll-Y-item"
            v-for="(item, index) in goodsList"
            :key="index"
          >
            <view class="content-item">
              <view class="content-item-left">
                <!-- <text class="goods-item-cz"
              >{{ item.dhCode ? "称重" : "计件" }} </text
            > -->
                <image
                  :src="item.cart_info.productAttr.image"
                  mode="scaleToFill"
              /></view>
              <view class="content-item-right">
                <view class="content-item-right-title">
                  <text>{{ item.cart_info.product.store_name }}</text>
                </view>

                <view class="content-item-right-num">
                  <view class="content-item-right-num-gg"
                    ><text>{{ item.cart_info.productAttr.sku }}</text>
                  </view>
                  <view class="content-item-right-num-left"
                    ><text>{{ item.categoryName }}</text>
                  </view>
                  <view class="content-item-right-num-right">
                    <up-number-box
                      v-model="item.num"
                      min="0"
                      :max="item.product_num"
                    ></up-number-box>
                  </view>
                </view>

                <view class="content-item-right-price">
                  <view
                    ><text>¥</text
                    >{{
                      item.cart_info.product.price
                        ? item.cart_info.product.price
                        : "0"
                    }}
                    &nbsp;
                  </view>
                  <view class="refund" v-if="item.is_refund >= 1"
                    >{{
                      item.is_refund == 1
                        ? "退款中"
                        : item.is_refund == 2
                        ? "部分退款"
                        : item.is_refund == 3
                        ? "退款"
                        : ""
                    }}x{{ item.total_num - item.refund_num }}</view
                  >
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
      <view class="goods_bt_to">
        <van-button class="val-button" type="primary" @click="goRecord"
          >确认核销</van-button
        >
      </view>
    </view>
  </up-popup>

  <up-popup
    :show="showNOIs"
    :closeOnClickOverlay="false"
    mode="bottom"
    @close="showNOIs = false"
    round="15rpx"
  >
    <view class="p_content">
      <view v-for="(item, index) in goodsList" :key="index">
        <view class="content-item">
          <view class="content-item-left">
            <!-- <text class="goods-item-cz"
              >{{ item.dhCode ? "称重" : "计件" }} </text
            > -->
            <image :src="item.cart_info.productAttr.image" mode="scaleToFill"
          /></view>
          <view class="content-item-right">
            <view class="content-item-right-title">
              <text>{{ item.cart_info.product.store_name }}</text>
            </view>
            <view>{{ item.cart_info.productAttr.sku }}</view>
            <view class="content-item-right-num">
              <view class="content-item-right-num-left"
                ><text>{{ item.categoryName }}</text>
              </view>
              <view class="content-item-right-num-right">
                <up-number-box
                  v-model="item.num"
                  min="0"
                  :max="item.product_num"
                ></up-number-box>
              </view>
            </view>

            <view class="content-item-right-price"
              ><text>¥</text
              >{{
                item.cart_info.product.price
                  ? item.cart_info.product.price
                  : "0"
              }}
              &nbsp;
            </view>
          </view>
        </view>
      </view>
    </view>
  </up-popup>
</template>

<style lang="scss" scoped>
@import "./index.scss";
</style>
